<?php
/**
* 2017年5月22日 13:44:05
* author:silenceluo
* email:1095584081@qq.com
* 微信公用接口
*/

require_once(WECHAT_ROOT.'Config/Config.php');

class WechatCommon
{
	//CI句柄
	private $_CI;

	//请求地址主机名
	private $host = 'https://api.weixin.qq.com/';

	private $_config;	微信配置

	function __construct($config)
	{	
		$this->config = $config;

		//获取CI句柄
		$this->_CI = & get_instance();
	}

	/**
	 * 获取微信接口参数
	 * @return [type] [description]
	 */
	public function getSignPackage()
	{
		$jsapiTicket = $this->getJsApiTicket();
		// 注意 URL 一定要动态获取，不能 hardcode.
		$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

		$timestamp = time()."";
		$nonceStr = generateNonceStr();
		
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
		
		$signature = sha1($string);

		$signPackage = array(
		  "appId"     => $this->config['appid'],
		  "nonceStr"  => $nonceStr,
		  "timestamp" => $timestamp,
		  "url"       => $url."/",
		  "signature" => $signature,
		  "rawString" => $string
		);
		return $signPackage; 
	}

	/**
	 * 获取js接口票据
	 * @return [type] [description]
	 */
	function getJsApiTicket() 
	{
		//获取数据库ticket信息
		$where = array(
			'id'=>1,
			);
		$data = $this->_CI->db->where($where)->get('token')->row_array();
		
		if ( ($data == '') || ($data == null) || ($data['ticket_time']<=time()))
		{
			$accessToken = $this->getAccessToken();
			$res = $this->getTicket($accessToken);
			$data = array(
				'ticket' => $res['ticket'],
				'ticket_time' => time()+7000,
				);
			//更新ticket
			$add_res = $this->_CI->db->where($where)->update('token',$data);
			
			if ($this->_CI->db->affected_rows() > 0)
			{
				return $res['ticket'];
			}
			else
			{
				return FALSE;
			}
		}
		else
		{	
			//ticket没过期 直接返回ticket
			return $data['ticket'];
		}
	}

	/**
	 * 获取微信票据token
	 * @return [type] [description]
	 */
	public function getAccessToken() {
		//从数据库中取token
		$where = array(
			'id'=>1,
			);
		$data = $this->_CI->db->where($where)->get('token')->row_array();
		
		//如果查询结果为空，则获取access_token并写入数据库
		if ( ($data == '') || ($data == null) )
		{	
			//token不存在  新增token记录
			$token = $this->getToken();
			$insert = array(
				'access_token' => $token,
				'token_time' => time()+7000,
				);
			$add_res = $this->_CI->db->insert('token',$insert);

			return $add_res?$token:FALSE;
		}
		elseif ($data['token_time']<=time())
		{
			//token过期 重新获取并更新
			$token = $this->getToken();
			$update = array(
				'access_token' => $token,
				'token_time' => time()+7000,
				);
			$update_res = $this->_CI->db->where($where)->update('token',$update);
			
			if ($update_res > 0)
			{
				return $token;
			}
			else
			{
				return FALSE;
			}
		}
		else
		{	
			//token存在且没过期  直接返回
			return $data['access_token'];
		}
	}

	/**
	 * 获取微信接口票据token
	 * @return [type] [description]
	 */
  	function getToken(){
  		$url = $this->_host.'cgi-bin/token?grant_type=client_credential&appid='.$this->config['appid'].'&secret='.$this->config['appsecret'];
  		//发送http请求
		$request = new Request();
		$token = $request->_get($url);

  		return $token['access_token'];
  	}

  	/**
  	 * 获取js票据
  	 * @param  [type] $access_token [description]
  	 * @return [type]               [description]
  	 */
	function getTicket($access_token){
		//如果是企业号用以下 URL 获取 ticket
		//$url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
		$url = $this->host."cgi-bin/ticket/getticket?type=jsapi&access_token=".$access_token;
		$request = new Request();

		return $request->_get($url);
	}
}